#!/usr/bin/env mksh

LC_ALL=C
LANG=C

f=('Menu 1' 'Menu 2' 'Menu 3' 'Menu 4' 'Menu 5' 'Menu 6')

refresh()
{
	# printf '\e[?7l\e[?25l\e[2J\e[H'
	printf '\e[?7l\e[?25l\e[u'
}

show()
{
	((c=${#f[@]},j=j>c?c:j))

	# printf '\e[K\e[m\e[H'
	printf '\e[K\e[m\e[u'

	for i in "${f[@]}"; do
		[[ "$i" == "${f[LINE]}" ]] && fo+='\e[7m'
		printf '\e[K%b%s\e[m\n' "$fo" "$i"; fo=
	done

	printf '\e[K\e['"$((LINES-1));$((COLUMNS-1))H"'\e[m'
}

key()
{
	case "${1: -1}" in
		"") return 1 ;;
		q) exit ;;

		j) : $((LINE=LINE==c-1?LINE:++LINE)) ;;
		k) : $((LINE < 1 ? LINE : --LINE)) ;;
	esac
}

main()
{
	trap "printf '\\e[u\\e[m\\e[?25h\\e[?7h\\e[J'" EXIT

	# Save current position
	printf '\e[s'
	refresh
	show

	while true; do
		read -rsn 1
		key "$REPLY" || break
		show
	done
}

select2()
{
	# trap "printf '\\e[u\\e[m\\e[?25h\\e[?7h\\e[J'; exec 3>&-" EXIT

	local ITEM
	local ITEMS
	local LINE
	local STYLE

	ITEMS=("$@")

	print_options()
	{
		printf '\e[K\e[m\e[u'

		for ITEM in "${ITEMS[@]}"; do
			[[ "$ITEM" == "${ITEMS[$LINE]}" ]] && STYLE+='\e[7m'
			printf '\e[K%b%s\e[m\n' "$STYLE" "$ITEM"; STYLE=
		done

		printf '\e[K\e['"$((LINES-1));$((COLUMNS-1))H"'\e[m'
	}

	# Save current position
	printf '\e[s'

	# Disable the cursor feedback
	printf '\e[?7l\e[?25l\e[u'

	print_options

	while true; do
		read -rsn 1
		case "${REPLY}" in
			"") REPLY="${ITEMS[$LINE]}"; break ;;
			q) REPLY= ; break ;;

			j) : $((LINE=LINE==$#-1?LINE:++LINE)) ;;
			k) : $((LINE < 1 ? LINE : --LINE)) ;;
		esac || break
		print_options
	done

	printf '\e[u\e[m\e[?25h\e[?7h\e[J'
}

# main "$@"

printf 'Iniciando...\e[m'
read -rt '2' -N 999
printf '[\e[38;5;1mok\e[m]\n'
select2 'Menu 1' 'Menu 2' 'Menu 3' 'Menu 4' 'Menu 5' 'Menu 6'

[[ -n $REPLY ]] && printf "O item selecionado foi: $REPLY\n" || printf "Cancelou seu arrombado\n"
